package com.rachel.utilslib.viewpager;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import java.util.List;

/**
 * Created by zhengshaorui on 2017/10/18.
 */

public class AutoPagerAdapter extends PagerAdapter {
    public static final int LOOP_COUNT = 5000;

    private  List<View> mViews;

    public AutoPagerAdapter(List<View> views) {
        this.mViews = views;
    }

    @Override
    public int getCount() {
        return LOOP_COUNT + mViews.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = null;
        if (mViews != null){
            //对Viewpager页号求模去除View列表中要显示的项
            position %= this.mViews.size();

            //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
            view = this.mViews.get(position);
            ViewParent viewParent = view.getParent();
            if (viewParent!=null){
                ViewGroup viewGroup = (ViewGroup) viewParent.getParent();
                viewGroup.removeAllViews();
            }
        }
        container.addView(view);
        return view;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //int index = position % mViews.size();
       // container.removeView(mViews.get(index));
        container.removeView((View) object);

    }
}
